package com.siashan.toolkit.captcha.easy;

import com.siashan.toolkit.captcha.cache.CaptchaCacheTemplate;
import com.siashan.toolkit.captcha.core.CaptchaCkResult;
import com.siashan.toolkit.captcha.core.CaptchaData;
import com.siashan.toolkit.captcha.core.CaptchaInfo;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Easy图形验证码构造器
 *
 * @author siashan
 * @since v1.0.5
 **/
@Setter
@Getter
public class EasyCaptchaTemplate {

    @Autowired
    private CaptchaCacheTemplate captchaCacheTemplate;

    /**
     * 渲染图形验证码
     *
     * @return CaptchaInfo
     */
    public CaptchaInfo render() {
        EasyCaptcha captcha = EasyCaptchaBuilder.build();
        CaptchaData render = EasyCaptchaUtil.render(captcha.getKaptcha());
        CaptchaInfo captchaInfo = render.getCaptchaInfo();
        captchaCacheTemplate.put(captchaInfo.getUuid(),render.getCaptchaText(),3);
        return captchaInfo;
    }

    /**
     * 渲染图形验证码
     *
     * @param captchaType 验证码类型
     * @return CaptchaInfo
     */
    public  CaptchaInfo render(EasyCaptchaType captchaType) {
        EasyCaptcha captcha = EasyCaptchaBuilder.build(captchaType);
        CaptchaData render = EasyCaptchaUtil.render(captcha.getKaptcha());
        CaptchaInfo captchaInfo = render.getCaptchaInfo();
        captchaCacheTemplate.put(captchaInfo.getUuid(),render.getCaptchaText());
        return captchaInfo;
    }

    /**
     * 校验图形验证码
     *
     * @param key 验证码类型
     * @return CaptchaCkResult
     */
    public CaptchaCkResult validate(String key,String value) {
        String sv = captchaCacheTemplate.get(key);
        captchaCacheTemplate.release(key);
        if (null == sv || "".equals(sv.trim())){
            return CaptchaCkResult.empty();
        }
        if (sv.equalsIgnoreCase(value)){
            return CaptchaCkResult.success();
        }else{
            return CaptchaCkResult.fail();
        }
    }
}
